<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>用户管理</title>
    <link rel="stylesheet" href="/component/pear/css/pear.css"/>
    <style>
        .layui-layer-loading .layui-layer-content {
            width: 200px;
            font-size: 18px;
            color: #795548;
        }
    </style>
</head>
<body class="pear-container">
<div class="layui-card">
    <div class="layui-card-body">
        <form class="layui-form" action="">
            <div class="layui-form-item">
                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label">档案名字</label>
                    <div class="layui-input-inline">
                        <input type="text" name="fileName" placeholder="" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label">选择机柜</label>
                    <div class="layui-input-inline">
                        <select name="number" lay-search lay-filter="cabinetChange">
                            <option value="">请选择机柜编号</option>
                            <option th:each="dict:${hostList}" th:value="${dict.number}" th:text="${dict.number}">
                        </select>
                    </div>
                </div>
                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label">时间</label>
                    <div class="layui-inline" id="test6">
                        <div class="layui-input-inline">
                            <input type="text" autocomplete="off" id="startDate" name="startDate" class="layui-input"
                                   placeholder="开始日期">
                        </div>
                        <div class="layui-form-mid">-</div>
                        <div class="layui-input-inline">
                            <input type="text" autocomplete="off" id="endDate" name="endDate" class="layui-input"
                                   placeholder="结束日期">
                        </div>
                    </div>
                </div>
                <div class="layui-form-item layui-inline">
                    <button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="search">
                        <i class="layui-icon layui-icon-search"></i>
                        查询
                    </button>
                    <button type="reset" class="pear-btn pear-btn-md">
                        <i class="layui-icon layui-icon-refresh"></i>
                        重置
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>
<div class="layui-card">
    <div class="layui-card-body">
        <table id="validArchives" lay-filter="validArchives"></table>
    </div>
</div>
<script type="text/html" id="validArchives-toolbar">
    <button class="pear-btn pear-btn-primary pear-btn-md" lay-event="add">
        <i class="layui-icon layui-icon-add-1"></i>
        新增档案
    </button>
    <!--    <button class="pear-btn pear-btn-md" lay-event="batchAdd" style="border: 1px solid #00BCD4 !important;-->
    <!--    background-color: #00BCD4 !important;color: #fff !important;">-->
    <!--        <i class="layui-icon layui-icon-add-1"></i>-->
    <!--        批量下发-->
    <!--    </button>-->
</script>
<script type="text/html" id="validArchives-bar">
    {{#if (d.status == 0) { }}
    <button plain class="pear-btn pear-btn-success pear-btn-xs" lay-event="takeOut">取出档案</button>&nbsp;&nbsp;
    {{# }else if(d.status == 1){ }}
    <button plain class="pear-btn pear-btn-success pear-btn-xs" lay-event="returnFile">归还档案</button>&nbsp;&nbsp;
    {{# } }}
    <button plain class="pear-btn pear-btn-primary  pear-btn-xs" lay-event="updateFile">修改档案</button>&nbsp;&nbsp;
    <button plain class="pear-btn pear-btn-danger pear-btn-xs" lay-event="remove">删除档案</button>
</script>
<script src="/component/layui/layui.js"></script>
<script src="/component/pear/pear.js"></script>
<script>
    layui.use(['table', 'form', 'jquery', 'common', 'laydate', 'element'], function () {
        let table = layui.table;
        let form = layui.form;
        let $ = layui.jquery;
        let common = layui.common;
        let upload = layui.upload;
        let laydate = layui.laydate;
        let element = layui.element;
        //日期范围
        laydate.render({
            elem: '#test6',
            //设置开始日期、日期日期的 input 选择器
            //数组格式为 2.6.6 开始新增，之前版本直接配置 true 或任意分割字符即可
            range: ['#startDate', '#endDate'],
            max: maxDate(),
            theme: '#000000'
        });

        // 设置最大可选的日期
        function maxDate() {
            var now = new Date();
            return now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate();
        }


        let validCols = [
            [
                {title: '档案名', field: 'file_name', align: 'center', sort: true},
                {title: '录入时间', field: 'entry_time', align: 'center', sort: true},
                {title: '机柜编号', field: 'number', align: 'center', sort: true},
                {title: '列编号', field: 'file_position', align: 'center', sort: true},
                {
                    title: '档案状态', field: 'status', align: 'center', sort: true, templet: function (d) {
                        if (d.status == 0) {
                            return '<span style="color: #069b23;">在柜</span>';
                        } else {
                            return '<span style="color: #e30707;">未在柜</span>'
                        }
                    }
                },
                {title: '操作', fixed: 'right', align: 'center', minWidth: 310, toolbar: '#validArchives-bar'}
            ]
        ]

        function validArchives() {
            table.render({
                elem: '#validArchives',
                url: '/file/manage/list',
                // height: 'full-175',
                page: true,
                limits: [40,80,120,160,200,300,400,500],
                limit: 40,
                cols: validCols,
                skin: 'line',
                toolbar: '#validArchives-toolbar',
                defaultToolbar: [{
                    title: '刷新',
                    layEvent: 'refresh',
                    icon: 'layui-icon-refresh',
                }, 'filter', 'print', 'exports'],
                id: 'valid',
                text: {
                    none: '暂无相关数据' //默认：无数据。
                },
            });
        }

        validArchives();
        table.on('tool(validArchives)', function (obj) {
            if (obj.event === 'remove') {
                window.remove(obj);
            } else if (obj.event === 'takeOut') {
                window.takeOut(obj);
            } else if (obj.event === 'returnFile') {
                window.returnFile(obj);
            } else if (obj.event === 'updateFile') {
                window.updateFile(obj);
            } else if (obj.event === 'uploadElectronFile') {
                window.uploadElectronFile(obj);
            }
        });
        table.on('toolbar(validArchives)', function (obj) {
            if (obj.event === 'add') {
                window.add();
            } else if (obj.event === 'batchAdd') {
                window.batchAdd();
            } else if (obj.event === 'refresh') {
                window.refresh();
            }
        });
        // 上传电子档案
        window.uploadElectronFile = function (obj) {
            layer.open({
                type: 2,
                title: '上传电子档案',
                shade: 0.1,
                area: [common.isModile() ? '100%' : '500px', common.isModile() ? '100%' : '400px'],
                content: '/file/manage/upload/electron?id=' + obj.data['id'],
                success: function (layero, index) {
                    layer.full(index); // 最大化
                }
            });
        }
        //搜索
        form.on('submit(search)', function (data) {
            table.reload('valid', {
                page: {
                    curr: 1 // 重新从第 1 页开始
                },
                where: data.field
            })
            return false;
        });
        window.add = function () {
            layer.open({
                type: 2,
                title: '档案录入',
                shade: 0.1,
                maxmin: true, //开启最大化最小化按钮
                area: [common.isModile() ? '100%' : '949px', common.isModile() ? '100%' : '550px'],
                // area: [common.isModile() ? '100%' : '949px', common.isModile() ? '100%' : 'auto'],
                content: '/file/manage/insert'
            });
        }
        // 批量下发
        window.batchAdd = function () {
            layer.open({
                type: 2,
                title: '批量下发',
                shade: 0.1,
                maxmin: true, //开启最大化最小化按钮
                area: [common.isModile() ? '100%' : '949px', common.isModile() ? '100%' : '550px'],
                // area: [common.isModile() ? '100%' : '949px', common.isModile() ? '100%' : 'auto'],
                content: '/file/manage/batch/instart'
            });
        }

        // 单个取出文件定时器
        function fileTimer(paramsMap) {
            timerId = setInterval(function () {
                $.ajax({
                    url: '/file/manage/takeout/status',
                    data: JSON.stringify(paramsMap),
                    dataType: 'json',
                    contentType: "application/json;charset=utf-8",
                    type: 'post',
                    success: function (result) {
                        var audio = document.createElement("audio");
                        if (result.code === 200) {
                            clearInterval(timerId); //清除计时器
                            layer.closeAll('loading');
                            layer.msg(result.message, {icon: 1, time: 3000});
                            layui.table.reload("valid");
                            sleep(1000);
                            wsIp = result.data;
                            openSocket();
                        } else if (result.code === 203) {
                            clearInterval(timerId); //清除计时器
                            layer.closeAll('loading');
                            layui.table.reload("valid");
                            // 语音播报
                            audio.src = '/MP3/未取走档案门已关闭.mp3';
                            audio.volume = 1;
                            audio.play();
                        }
                        console.log(result)
                    }
                })
            }, 5000);
        }

        // 取出档案
        window.takeOut = function (obj) {
            var str = '<div>确定取出<span  style="color: #e10a27"> ' + obj.data.file_name + ' </span>档案吗？</div>';
            layer.confirm(str, {
                icon: 3,
                title: '提示'
            }, function (index) {
                layer.close(index);
                let loading = layer.load();
                $.ajax({
                    url: '/file/manage/takeout/view',
                    data: JSON.stringify({"id": obj.data.id}),
                    dataType: 'json',
                    type: 'post',
                    contentType: 'application/json',
                    success: function (result) {
                        var audio = document.createElement("audio");
                        layer.close(loading);
                        if (result.code === 200) {
                            let number = obj.data.number.replace(/\D/g, '');
                            let doorColumnAudio = document.createElement("audio");
                            doorColumnAudio.src = '/MP3_takeout/请前往' + number + '号柜领取档案.mp3';
                            doorColumnAudio.volume = 1;
                            doorColumnAudio.play();
                            layer.load(2, {shade: [0.5, '#393D49'], content: '请前往柜体端领取档案'});
                            result.data["requestType"] = "1";
                            fileTimer(result.data);
                        } else {
                            layer.msg(result.message, {
                                icon: 2,
                                time: 3000
                            });
                        }
                    }
                })
            });
        }
        // 归还档案
        window.returnFile = function (obj) {
            var str = '<div>确定归还<span  style="color: #e10a27"> ' + obj.data.file_name + ' </span>档案吗？</div>';
            layer.confirm(str, {
                icon: 3,
                title: '提示'
            }, function (index) {
                layer.close(index);
                let loading = layer.load();
                $.ajax({
                    url: '/file/manage/returnFile?id=' + obj.data.id,
                    data: JSON.stringify({"id": obj.data.id}),
                    dataType: 'json',
                    contentType: 'application/json',
                    type: 'post',
                    success: function (result) {
                        layer.close(loading);
                        if (result.code === 200) {
                            let number = obj.data.number.replace(/\D/g, '');
                            let doorColumnAudio = document.createElement("audio");
                            doorColumnAudio.src = '/MP3_return/请前往' + number + '号柜归还档案.mp3';
                            doorColumnAudio.volume = 1;
                            doorColumnAudio.play();
                            layer.load(2, {shade: [0.5, '#393D49'], content: '请前往柜体端归还档案'});
                            result.data["requestType"] = "2";
                            fileTimer(result.data);
                        } else {
                            layer.msg(result.message, {
                                icon: 2,
                                time: 3000
                            });
                        }
                    }
                })

            });

        }
        // 删除档案
        window.remove = function (obj) {
            layer.confirm('确定要删除该文件', {
                icon: 3,
                title: '提示'
            }, function (index) {
                layer.close(index);
                let loading = layer.load();
                $.ajax({
                    url: "/file/manage/delete/" + obj.data['id'],
                    dataType: 'json',
                    type: 'delete',
                    success: function (result) {
                        layer.close(loading);
                        if (result.code === 200) {
                            layer.msg(result.message, {
                                icon: 1,
                                time: 3000
                            }, function () {
                                obj.del();
                                table.reload("valid");
                            });
                        } else {
                            layer.msg(result.message, {
                                icon: 2,
                                time: 3000
                            });
                        }
                    }
                })
            });
        }
        // 修改档案
        window.updateFile = function (obj) {
            layer.open({
                type: 2,
                title: '修改档案',
                shade: 0.1,
                area: ['500px', '500px'],
                content: '/file/manage/edit?id=' + obj.data['id']
            });
        }

        window.refresh = function (param) {
            table.reload('valid');
        }
        // 无效档案
        let invalidCols = [
            [
                {title: '档案名称', field: 'fileName', align: 'left'},
            ]
        ]
        $(".invalidFile").click(function () {
            invalidFile();
        })

        function invalidFile() {
            table.render({
                elem: '#invalidFile',
                url: '/file/manage/invalid/list',
                height: 'full-230',
                page: true,
                limits: [40],
                limit: 40,
                cols: invalidCols,
                skin: 'line',
                defaultToolbar: [{
                    title: '刷新',
                    layEvent: 'refresh',
                    icon: 'layui-icon-refresh',
                }, 'filter', 'print', 'exports'],
                id: 'valid',
                text: {
                    none: '暂无相关数据' //默认：无数据。
                },
            });
        }

        function guid() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = Math.random() * 16 | 0,
                    v = c == 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        }

        uuid = guid();
        let socket;
        let wsIp = "";

        // 关门盘库使用
        function openSocket() {
            const socketUrl = "ws://" + wsIp + "/api/pushMessage/" + uuid;

            console.log(socketUrl);
            if (socket != null) {
                socket.close();
                socket = null;
            }
            socket = new WebSocket(socketUrl);
            //打开事件
            socket.onopen = function () {
                console.log("websocket已打开");
                let msg = {'command': 'startInventoryCheck'};
                sendMessage(JSON.stringify(msg));
            };
            //获得消息事件
            socket.onmessage = function (msg) {
            };
            //关闭事件
            socket.onclose = function () {
                console.log("websocket已关闭");
            };
            //发生了错误事件
            socket.onerror = function () {
                console.log("websocket发生了错误");
            }
        }

        function sendMessage(sendMsg) {
            socket.send(sendMsg);
        }

        //程序睡眠
        function sleep(time) {
            var timeStamp = new Date().getTime();
            var endTime = timeStamp + time;
            while (true) {
                if (new Date().getTime() > endTime) {
                    return;
                }
            }
        }
    })
</script>
</body>
</html>
